package com.mbl.base.config.security;

import com.mbl.base.core.common.exception.AuthException;
import com.mbl.base.core.utils.FactoryUser;
import com.mbl.base.modular.base.entity.Permission;
import com.mbl.base.modular.base.entity.Role;
import com.mbl.base.modular.base.service.IAdminService;
import com.mbl.base.modular.base.service.IPermissionService;
import com.mbl.base.modular.base.service.IRoleService;
import com.mbl.base.modular.member.entity.User;
import com.mbl.base.modular.member.service.IUserService;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    private Map<String, SecurityUser> map = new HashMap<>();

    /**
     * 用户登录前缀
     */
    public static final String USERNAME_PRE = "mblu2_";
    @Autowired
    private IUserService userService;
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SecurityUser userDetails = map.get(username);
        if(userDetails != null){
            return userDetails;
        }
        if(StringUtils.startsWith(username, USERNAME_PRE)){
            /**
             * 用户登录逻辑(用户名前缀 mblu2_ )
             */
            User user = userService.query().eq("username", StringUtils.removeStart(username, USERNAME_PRE)).one();
            if(user == null || user.getId() == null){
                throw new AuthException();
            }
            userDetails = FactoryUser.createUser(user);
            userDetails.setUsername(username);
            userDetails.getPerms().add("user:all");
        } else {
            /**
             * 管理员登录逻辑
             */
            final com.mbl.base.modular.base.entity.Admin adminEntity = adminService.query().eq("username", username).one();
            if(adminEntity == null || adminEntity.getId() == null){
                throw new AuthException();
            }
            userDetails = FactoryUser.createUser(adminEntity);
            // 角色赋值
            final Integer[] roleIds = adminEntity.getRoleIds();
            if(roleIds.length > 0){
                final List<Role> roles = (List<Role>) roleService.listByIds(Arrays.asList(roleIds));
                userDetails.setRoles(roles);
                // 权限赋值
                Set<String> permIdSet = new HashSet();
                for (int i = 0; i < roles.size(); i++) {
                    final String perids = roles.get(i).getPerids();
                    if(StringUtils.isNotBlank(perids)){
                        permIdSet.addAll(Arrays.asList(perids.split(",")));
                    }
                }
                if(permIdSet.size() > 0){
                    final Collection<Permission> permissions = permissionService.listByIds(permIdSet);
                    final List<String> permStrs = permissions.stream().map(permission -> permission.getPermission()).collect(Collectors.toList());
                    userDetails.setPerms(permStrs);
                }
            }
        }
        map.put(username, userDetails);
        return userDetails;
    }
}
